package org.example.rzfx.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.rzfx.dto.Result;
import org.example.rzfx.service.LogCacheService;
import org.example.rzfx.task.LogWriteBackTask;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日志缓存监控控制器
 * 
 * 功能：
 * 1. 查看Redis缓存的日志统计
 * 2. 手动触发回写任务
 * 3. 查看回写任务状态
 */
@RestController
@RequestMapping("/api/log/cache")
@Slf4j
public class LogCacheController {
    
    @Resource
    private LogCacheService logCacheService;
    
    @Resource
    private LogWriteBackTask logWriteBackTask;
    
    /**
     * 获取缓存统计信息
     * 
     * @return 统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getCacheStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 待回写的日期列表
            List<String> pendingDates = logCacheService.getPendingDates();
            stats.put("pendingDates", pendingDates);
            stats.put("pendingDateCount", pendingDates.size());
            
            // 每个日期的日志数量
            Map<String, Long> dateCountMap = new HashMap<>();
            long totalCount = 0;
            for (String date : pendingDates) {
                long count = logCacheService.getCachedLogCount(date);
                dateCountMap.put(date, count);
                totalCount += count;
            }
            stats.put("dateLogCounts", dateCountMap);
            stats.put("totalCachedCount", totalCount);
            
            // 回写任务状态
            stats.put("isWriteBackRunning", logWriteBackTask.isRunning());
            
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取缓存统计失败", e);
            return Result.error("获取统计信息失败");
        }
    }
    
    /**
     * 获取指定日期的缓存日志数量
     * 
     * @param date 日期，格式：yyyy-MM-dd
     * @return 日志数量
     */
    @GetMapping("/count/{date}")
    public Result<Long> getCacheCount(@PathVariable String date) {
        try {
            long count = logCacheService.getCachedLogCount(date);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取日期 {} 的缓存日志数量失败", date, e);
            return Result.error("获取日志数量失败");
        }
    }
    
    /**
     * 手动触发回写任务
     * 
     * @return 结果
     */
    @PostMapping("/writeback")
    public Result<String> triggerWriteBack() {
        try {
            if (logWriteBackTask.isRunning()) {
                return Result.error("回写任务正在执行中，请稍后再试");
            }
            
            // 异步执行回写任务
            new Thread(() -> {
                logWriteBackTask.manualWriteBack();
            }).start();
            
            return Result.success("回写任务已启动");
            
        } catch (Exception e) {
            log.error("触发回写任务失败", e);
            return Result.error("触发回写任务失败");
        }
    }
    
    /**
     * 获取回写任务状态
     * 
     * @return 状态信息
     */
    @GetMapping("/writeback/status")
    public Result<Map<String, Object>> getWriteBackStatus() {
        try {
            Map<String, Object> status = new HashMap<>();
            status.put("isRunning", logWriteBackTask.isRunning());
            status.put("pendingStatus", logWriteBackTask.getPendingStatus());
            
            // 添加最后一次执行结果
            LogWriteBackTask.WriteBackResult lastResult = logWriteBackTask.getLastResult();
            if (lastResult != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("totalProcessed", lastResult.getTotalProcessed());
                result.put("totalSuccess", lastResult.getTotalSuccess());
                result.put("totalFailed", lastResult.getTotalFailed());
                result.put("durationSeconds", lastResult.getDurationSeconds());
                result.put("completeTime", lastResult.getCompleteTime());
                result.put("error", lastResult.getError());
                status.put("lastResult", result);
            }
            
            return Result.success(status);
            
        } catch (Exception e) {
            log.error("获取回写任务状态失败", e);
            return Result.error("获取状态失败");
        }
    }
    
    /**
     * 删除指定日期的缓存
     * 
     * @param date 日期
     * @return 结果
     */
    @DeleteMapping("/cache/{date}")
    public Result<String> deleteCachedLogs(@PathVariable String date) {
        try {
            boolean success = logCacheService.deleteCachedLogs(date);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除日期 {} 的缓存失败", date, e);
            return Result.error("删除缓存失败");
        }
    }
}

